package org.example.Swing.handler;

import org.example.Swing.xiangmu.login.AddKcView;
import org.example.Swing.xiangmu.login.AddView;
import org.example.Swing.xiangmu.login.MainView;
import org.example.controller.GradeController;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class AddHandler extends KeyAdapter implements ActionListener {
    private final AddView addView;
    private final MainView mainView;

    public AddHandler(AddView addView, MainView mainView) {
        this.addView = addView;
        this.mainView = mainView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("添加".equals(text)) {
            add();
        } else if ("添加课程".equals(text)) {
            new AddKcView(addView);
        }
    }

    public void add() {
        mainView.dispose();
        GradeController gradeController = new GradeController();
        String stuName = addView.getNameTxt().getText();
        String stuNo = addView.getNoText().getText();
        String kcTxt = addView.getKcTxt().getText();
        double psText = Double.parseDouble(addView.getPstext().getText());
        double ksText = Double.parseDouble(addView.getKstext().getText());
        if (stuName != null && stuNo != null && kcTxt != null && psText != 0 && ksText != 0) {
            int i = gradeController.insertByDate(stuName, stuNo, kcTxt, psText, ksText);
            if (i > 0) {
                JOptionPane.showMessageDialog(addView, "添加成功！");
                addView.dispose();
                new MainView();
            } else {
                JOptionPane.showMessageDialog(addView, "添加失败！");
            }
        } else {
            JOptionPane.showMessageDialog(addView, "不能为空！");
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            add();
        }
    }
}
